<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Option;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class OptionsController extends Controller
{
    /**
     * 配置信息
     *
     * @return array
     */
    public function index()
    {
        $default = [
            'app_name' => '',
            'share_title' => '',
            'share_image' => '',
            'share_description' => '',
            'register_award' => 0,    // 注册奖励，如果小于等于 0，表示没有注册奖励；大于 0，表示奖励游戏币个数
            'auditing_version_android' => '',
            'auditing_version_ios' => '',
            'doll_records_sentences' => '',
        ];
        
        $options = load_all_options();
        
        $data = array_only_merge($default, $options);
        
        $data['share_image'] = image_url($data['share_image']);
        
        return $this->wrapData($data);
    }
    
    /**
     * 更新配置信息
     *
     * @param Request $request
     */
    public function store(Request $request)
    {
        $inputs = $this->validate($request, [
            'app_name' => 'filled|string|max:30',
            'share_title' => 'nullable|string|max:30',
            'share_image_file' => 'image',
            'share_description' => 'nullable|string|max:100',
            'register_award' => 'integer|between:0,1000',
            'auditing_version_android' => 'nullable|string',
            'auditing_version_ios' => 'nullable|string',
            'doll_records_sentences' => 'nullable|string',
        ]);
        
        if ($request->hasFile('share_image_file')) {
            $shareImage = Option::findByName('share_image');
            $path = upload_image('share_image_file');
            
            // 删除旧的分享图
            if ($shareImage) {
                Storage::delete($shareImage->value);
            }
            
            $inputs['share_image'] = $path;
            unset($inputs['share_image_file']);
        }
        
        update_options($inputs);
    }
}
